package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementMapper statementMapper;

    @Override
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        return new TablePageInfo<>(statementItemMapper.selectForList(qo));
    }

    @Override
    @Transactional
    public void saveItems(List<StatementItem> list) {
        // 1 从集合中的最后一个元素中拿到优惠金额
        StatementItem statementItem = list.remove(list.size() - 1);
        BigDecimal disCountAmount = statementItem.getItemPrice();
        Long statementId = statementItem.getStatementId();
        // 删除旧关系 , 插入新关系
        statementItemMapper.deleteRelation(statementId);
        // 2 遍历计算出来总金额和总数量, 遍历过程中吧数据插入到中间表中
        BigDecimal totalAmount = new BigDecimal("0");
        BigDecimal totalCount =  new BigDecimal("0");
        for (StatementItem item : list) {
            totalAmount = totalAmount.add(item.getItemPrice().multiply(item.getItemQuantity()));
            totalCount = totalCount.add(item.getItemQuantity());
            statementItemMapper.insert(item);
        }
        // 3 修改结算单中 总金额 总数量  优惠金额
        statementMapper.updateAmount(totalAmount,totalCount,disCountAmount,statementId);

    }

    @Override
    public void pay(Long statementId) {
        //1 根据id 把结算单查询出来
        Statement statement = statementMapper.selectByPrimaryKey(statementId);
        //2 判断结算单状态必须是消费中
        if(!Statement.STATUS_CONSUME.equals(statement.getStatus())){
            throw new BusinessException("非法操作");
        }
        //3 修改结算单的状态 ,支付人, 支付时间
        statementMapper.changePayStatus(statementId,Statement.STATUS_PAID, ShiroUtils.getUserId());
    }
}
